package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import play.Play;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class HelpUtils {
	/**
	 * 获取错误信息
	 * @param jsonStr
	 * @return
	 */
	public static String getErrorMessage(String jsonStr){
		try{
			JSONObject json = JSONObject.parseObject(jsonStr);
			JSONArray array = json.getJSONArray("CommonReturnInfoTable");
			return ((JSONObject)array.get(0)).getString("ExcpetionData");
		}catch(Exception e){
			return "未知错误";
		}
	}
	
	/**
	 * 删除上传的文件 
	 * @param array
	 */
	public static void delFiles(JSONArray array){
		for(int i=0; i<array.size(); i++){
			JSONObject json = (JSONObject) array.get(i);
			File file = Play.getFile(json.getString("FilePath"));
			if(file.exists()){
				file.delete();
			}
		}
	}
	
	/**
	 * 打包zip
	 * @param jsonArray
	 * @param orderMainID
	 * @return
	 * @throws IOException
	 */
	public static File zip(JSONArray jsonArray, String id) throws IOException{
		String filePath = "tmp/"+id+ "_" + System.currentTimeMillis() + ".zip";
		File file = Play.getFile(filePath);
		ZipOutputStream zipos = new ZipOutputStream(new FileOutputStream(file));
		FileInputStream fis;
		File sFile;
		byte[] buf = new byte[1024];
		for(int i =0; i<jsonArray.size(); i++){
			JSONObject json = jsonArray.getJSONObject(i);
			sFile = Play.getFile(json.getString("FilePath"));
			if(!sFile.exists()){
				continue;
			}
			fis = new FileInputStream(sFile);
			zipos.putNextEntry(new ZipEntry(json.getString("FileWithExtension")));
			int len = 0;
			while((len=fis.read(buf))>0){
				zipos.write(buf, 0, len);
			}
			zipos.closeEntry();
			fis.close();
		}
		zipos.close();
		return file;
	}
}
